/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestBufferedReaderWriter.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package io.api;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * java.io.BufferedReader测试<br/>
 * java.io.BufferedWriter测试<br/>
 * 
 * 凡是缓冲流其自身都不具备读写文件的能力
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestBufferedReaderWriter {

	/**
	 * 使用BufferedReader & BufferedWriter拷贝文件
	 * 
	 * @param fileSource
	 * @param fileDest
	 */
	public static void copyFileByBufferReaderWriter(String fileSource, String fileDest) {
		BufferedReader in = null;
		BufferedWriter out = null; // 内部提供了一个8K的数组作为缓冲区

		try {
			in = new BufferedReader(new FileReader(fileSource));
			out = new BufferedWriter(new FileWriter(fileDest));

			String temp = in.readLine();
			while (temp != null) {
				out.write(new String(temp.getBytes(), "UTF-8"));
				out.newLine();
				temp = in.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 先关闭输出流, 再关闭输入流
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 自定义一个readline()方法
	 * 
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	public String readLine(FileReader reader) throws IOException {
		StringBuffer buffer = new StringBuffer();

		int content = 0;
		while ((content = reader.read()) != -1) {
			if (content == '\r') {
				continue;
			} else if (content == '\n') {
				break;
			} else {
				buffer.append((char) content);
			}
		}
		return buffer.toString();
	}
}
